<?php

namespace app\api\controller\partner;

use addons\qrcode\library\Service;
use app\admin\model\partner\Apply;
use app\admin\model\partner\file\Sign;
use app\admin\model\partner\level\Setting;
use app\admin\model\partner\stone\Log;
use app\admin\model\User;
use app\common\controller\Api;
use app\common\model\Activity as M;
use app\common\library\Partner as PartnerLib;
use Carbon\Carbon;
use fast\Random;
use think\App;
use think\Db;
use think\Image;
use think\Log as tLog;
use think\Lang;


/**
 * 公告接口
 */
class Partner extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['memberInfo', 'levels', 'qrcode'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    public function checkQualification()
    {
        $userId = $this->auth->id;
        $isPartner = \app\admin\model\user\Partner::get(['user_id' => $userId]);
        if ($isPartner) {
            $this->error('已经是合伙人，无需申请', null, -1);
        }

        $row = Apply::where('apply_id', $userId)
            ->order('id', 'desc')
            ->find();

        if (is_null($row)) {
            $this->error('你没有申请成为梦想VIP', [
                'partner_advantage' => config('site.partner_advantage')
            ]);
        }

        $this->success('ok', $row);
    }

    public function becomePartner()
    {
        $userId = $this->auth->id;
        $partner = \app\admin\model\user\Partner::get(['user_id' => $userId]);
        if ($partner) {
            $this->error('已经是合伙人，无需申请', null, -1);
        }

        $row = Apply::where('apply_id', $userId)
            ->order('id', 'desc')
            ->find();

        if (1 != $row->status) {
            $this->error('你还没有取得成为合伙人的资格');
        }

        $partner = \app\admin\model\user\Partner::get($row->partner_id);

        // 20250113修改为 我得上级批发商：统一显示为同一条推荐线上级别高于我且离我最近得批发商
        // $upLevelId = \app\admin\model\user\Partner::getNextLevel($partner->level_id);
        $upLevelId = 11;
        $upLevelObj = Setting::get($upLevelId);

        // 当前账户的推荐人ID路径
        $gePartnerId = null;
        if ($partner->dre_id_path) {
            $parentIdPathArr = explode(",", $partner->dre_id_path);

            // 查找所有同一条推荐线上的人的用户的级别
            $where = [
                'id' => ['in', $parentIdPathArr],
            ];
            $parentPartnersObj = \app\admin\model\user\Partner::where($where)->order('id', 'desc')->select();
            $parentPartners = [];
            foreach ($parentPartnersObj as $p) {
                $parentPartners[$p->id] = $p->level->level;
            }
            $msg = vsprintf("partner id: %s, 要升级的级别ID: %s, 定义级别值:%s", [$partner->id, $upLevelId, $upLevelObj->level]);
            // echo $msg . "<br />";
            tLog::write($msg);
            // 从路径开始找
            foreach ($parentIdPathArr as $parentId) {
                // 等级数值越小，等级越大的最近的上级批发商
                if (isset($parentPartners[$parentId]) && $parentPartners[$parentId] < $upLevelObj->level) {
                    $gePartnerId = $parentId;
                    break;
                }
            }
        } else {
            $gePartnerId = $partner->id;
        }


        \app\admin\model\user\Partner::create([
            'partner_account' => $this->auth->username, // 三号合一
            'status' => 1,
            'createtime' => Carbon::now()->timestamp,
            'updatetime' => Carbon::now()->timestamp,
            'user_id' => $userId,
            'level_id' => $upLevelId,
            // 'parent_id' => $row->partner_id,
            'parent_id' => $gePartnerId,
            'parent_id_path' => \app\admin\model\user\Partner::getTheParentPath($row->partner_id),
            'dre_id' => $row->partner_id,
            'dre_id_path' => \app\admin\model\user\Partner::getDreParentPath($row->partner_id),
        ]);

        // 保存是合伙人信息
        $user = User::get($userId);
        $user->is_partner = 1;
        $user->save();

        $this->success('成功成为合伙人');
    }

    public function baseinfo()
    {
        $userId = $this->auth->id;
        $partner = \app\admin\model\user\Partner::with(['user', 'level'])
            ->where('user_id', $userId)
            ->find();
        if (!$partner) {
            $this->error('当前用户还不是梦想VIP');
        }
        $info = $partner->toArray();

        //得到推荐人信息
        $dre = \app\admin\model\user\Partner::get($partner->dre_id, ['user', 'level']);
        $info['dre'] = $dre;

        // 20250115 修改为被动更新上级的逻辑
        $partnerLib = new PartnerLib(); 
        $partnerLib->updateParentId($partner->id);

        //得到上级信息
        $parent = \app\admin\model\user\Partner::get($partner->parent_id, ['user', 'level']);
        $info['parent'] = $parent;

        $this->success('ok', $info);
    }

    public function apply()
    {
        $userId = $this->auth->id;

        $realname = input('post.realname');
        $partnerAccount = input('post.partner_account');

        $isPartner = \app\admin\model\user\Partner::get(['user_id' => $userId]);
        if ($isPartner) {
            $this->error('已经是合伙人，无需申请');
        }

        $partner = \app\admin\model\user\Partner::where('partner_account', $partnerAccount)
            ->where('realname', $realname)
            ->where('status', 2)
            ->find();

        if (is_null($partner)) {
            $this->error('此邀约人信息不存在，请联系邀约人确认');
        }

        $hasInvited = Apply::where('apply_id', $userId)
            ->where('partner_id', $partner->id)
            ->whereIn('status', [0, 1]) //对拒绝的可以再次审请
            ->count();

        if ($hasInvited) {
            $this->error('此邀约人的申请已经存在，不需要重复提交');
        }

        Apply::create([
            'type' => 1,
            'status' => 0, //0为申请中
            'createtime' => Carbon::now()->getTimestamp(),
            'updatetime' => Carbon::now()->getTimestamp(),
            'apply_id' => $userId,
            'partner_id' => $partner->id,
        ]);

        $this->success('申请成功，等待邀约人同意');

    }

    public function assignRole()
    {
        $userId = $this->auth->id;

        $partner = \app\admin\model\user\Partner::get(['user_id' => $userId]);

        if (is_null($partner)) {
            $this->error('你还不是合伙人');
        }

        if ($partner->trans_card_amount <= 0) {
            $this->error('你当前可用兑换卡数量为0, 无法操作');
        }

        $mobile = input('post.mobile');
        $user = User::get(['username' => $mobile]);

        if (is_null($user)) {
            $this->error('你输入的手机号的用户不存在');
        }

        //是否已经是合伙人了 和 存在申请中
        $userPartner = \app\admin\model\user\Partner::get(['user_id' => $user->id]);
        if ($userPartner) {
            $this->error('此手机用户已经是合伙人了');
        }
        $hasApply = Apply::get(['apply_id' => $user->id, 'status' => 1]);
        if ($hasApply) {
            $this->error('此用户已经是合伙人或者已经拥入加入资格');
        }

        Apply::create([
            'type' => 2,
            'status' => 1,
            'createtime' => Carbon::now()->getTimestamp(),
            'updatetime' => Carbon::now()->getTimestamp(),
            'apply_id' => $user->id,
            'partner_id' => $partner->id,
        ]);

        $partner->trans_card_amount -= 1;
        $partner->save();

        $this->success('赋予成功，被赋予人可以直接加入成为合伙人');
    }

    public function waitingApplyList()
    {
        $userId = $this->auth->id;

        $partner = \app\admin\model\user\Partner::get(['user_id' => $userId]);
        if (is_null($partner)) {
            $this->error('还不是合伙人');
        }

        $list = Apply::with(['applyer'])
            ->where('partner_id', $partner->id)
            ->where('type', 1)
            ->select();

        // 因为字段冲突， 在这里把status=0的过滤出来
        $data = [];
        foreach ($list as $item) {
            if (0 == $item->status) {
                $data[] = $item;
            }
        }

        $this->success('ok', $data);

    }

    public function dealApply()
    {
        $userId = $this->auth->id;
        $partner = \app\admin\model\user\Partner::get(['user_id' => $userId]);


        $action = input('post.action');
        $applyUserId = input('post.apply_user_id');
        $rejectReason = input('post.reject_reason', null);

        if (!in_array($action, ['pass', 'reject']) or empty($applyUserId)) {
            $this->error('参数错误');
        }

        $apply = Apply::where('apply_id', $applyUserId)
            ->where('partner_id', $partner->id)
            ->where('status', 0)
            ->find();
        if (is_null($apply)) {
            $this->error('申请不存在');
        }


        if ('pass' == $action) {
            if ($partner->trans_card_amount <= 0) {
                $this->error('可用兑换卡数量不足');
            }
            $apply->status = 1;

            // 消耗一张卡
            $partner->trans_card_amount -= 1;
            $partner->save();

        } else if ('reject' == $action) {
            $apply->status = 2;
            $apply->reject_reason = $rejectReason;
        }

        $apply->save();

        $this->success('处理完成');

    }

    public function agreementlist()
    {
        $userId = $this->auth->id;
        $partner = \app\admin\model\user\Partner::get(['user_id' => $userId]);

        $row = Sign::get(['partner_id' => $partner->id]);

        $fileOneTitle = 'XXXX合伙人协议（1）';
        $fileOneContent = config('site.partner_agreement1');

        $fileTwoTitle = 'XXXX合伙人协议（2）';
        $fileTwoContent = config('site.partner_agreement2');

        if (is_null($row)) {
            $fileOneSigned = false;
            $fileTwoSigned = false;
        } else {
            $fileOneSigned = $row->file_one_signature_image ? true : false;
            $fileTwoSigned = $row->file_two_signature_image ? true : false;
        }

        $this->success('ok', [
            'file1' => [
                'title' => $fileOneTitle,
                'content' => $fileOneContent,
                'is_signed' => $fileOneSigned,
            ],
            'file2' => [
                'title' => $fileTwoTitle,
                'content' => $fileTwoContent,
                'is_signed' => $fileTwoSigned
            ]
        ]);


    }

    public function fileFile()
    {
        $userId = $this->auth->id;
        $partner = \app\admin\model\user\Partner::get(['user_id' => $userId]);

        $fileNo = input('post.file_no');
        $imageUrl = input('post.image_url');

        $row = Sign::get(['partner_id' => $partner->id]);

        if (1 == $fileNo) {
            $field = 'file_one_signature_image';
        } else if (2 == $fileNo) {
            $field = 'file_two_signature_image';
        }

        if ($row) {
            $row->{$field} = $imageUrl;
            $row->save();

            if (!empty($row->file_one_signature_image) and !empty($row->file_two_signature_image)) {
                $partner->is_file_signed = 1;
                //如果已经实名了，就直接把status设为正常
                if (2 == $partner->verify_status) {
                    $partner->status = 2; //正常
                }
                $partner->save();
            }
        } else {
            $sign = new Sign();
            $sign->{$field} = $imageUrl;
            $sign->partner_id = $partner->id;
            $sign->save();
        }
        $this->success('文件签名保存成功');
    }

    public function submitRealInfo()
    {
        $userId = $this->auth->id;
        $partner = \app\admin\model\user\Partner::get(['user_id' => $userId]);

        $realname = $this->request->post('realname');
        $idcardNo = $this->request->post('idcard_no');
        $idcardFrontImage = $this->request->post('idcard_front_image');
        $idcardBackImage = $this->request->post('idcard_back_image');

        if (empty($realname) or empty($idcardNo) or empty($idcardFrontImage) or empty($idcardBackImage)) {
            $this->error('参数不完整');
        }

        $isValididCard = (function ($idCard) {
            $pattern = '/^\d{17}(\d|X|x)$/';
            return preg_match($pattern, $idCard) === 1;
        })($idcardNo);

        if ($isValididCard) {
        } else {
            $this->error('身份证号码不对');
        }

        $partner->realname = $realname;
        $partner->idcard_no = $idcardNo;
        $partner->idcard_front_image = $idcardFrontImage;
        $partner->idcard_back_image = $idcardBackImage;
        $partner->verify_status = 1; //审核中

        $partner->save();

        $this->success('实名认证信息提交成功');
    }

    public function stoneLog()
    {
        $userId = $this->auth->id;

        $limit = 10;

        $page = input('get.page', 1);
        $fromTime = input('get.from_time');
        $toTime = input('get.to_time');

        $fromTimeStamp = Carbon::createFromDate($fromTime . ' 00:00:01')->timestamp;
        $toTimeStamp = Carbon::createFromDate($toTime . ' 23:23:59')->timestamp;
        $stoneType = input('get.stone_type', null);

        $model = new \app\admin\model\partner\stone\Log();

        $query = $model->where(function ($query) use ($userId) {
            $query->where('from_id', $userId)->whereOr('to_id', $userId);
        })
            ->whereBetween('createtime', [$fromTimeStamp, $toTimeStamp]);

        if (in_array($stoneType, [1, 2, 3])) {
            $query = $query->where('stone_type', $stoneType);
        }

        $log = $query->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page])
            ->each(function ($item, $key) {
                $item->from = \app\admin\model\user\Partner::get(['user_id' => $item->from_id]);
                $to = \app\admin\model\user\Partner::get(['user_id' => $item->to_id]);
                if (is_null($to)) { // 普通用户
                    $user = User::get($item->to_id);
                    $item->to->role = 'normal'; //普通用户
                    $item->to->realname = $user->username;
                    $item->to->account = $user->username;
                } else {  // 合伙人
                    $item->to = new \stdClass();
                    $item->to->role = 'vip'; //梦想vip
                    $item->to->realname = $to->realname;
                    $item->to->account = $to->partner_account;
                }
            });

        if (count($log)) {
            $this->success('ok', $log);
        } else {
            $this->error('没有更多数据');
        }

    }

    public function stoneTransfer()
    {
        $userId = $this->auth->id;
        $partner = \app\admin\model\user\Partner::get(['user_id' => $userId], ['user', 'level']);
        if (is_null($partner) or 2 != $partner->status) {
            $this->error('当前用户还没有辈分或者非正常状态');
        }

        $toAccount = input('post.to_partner_account');
        $stoneType = input('post.stone_type');
        $amount = input('post.amount/d');
        $notice = input('post.notice');

        $toUser = User::get(['username' => $toAccount]);
        if (is_null($toUser)) {
            $this->error('收款帐号不存在');
        }

        if (!(is_int($amount) and $amount > 0)) {
            $this->error('转账的石头数量必须是大于0的整数');
        }

        if (1 == $stoneType) {
            $field = 'green_stone_amount';
        } else if (2 == $stoneType) {
            $field = 'blue_stone_amount';
        } else if (3 == $stoneType) {
            $field = 'red_stone_amount';
        } else {
            $this->error('请提供合法的石头类型');
        }

        if ($partner->user->{$field} < $amount) {
            $this->error('付款方此类型石头数量不足, 当前数量为：' . $partner->user->{$field});
        }

        // 付款账号的等级
        $curPartnerId = $partner->id;
        $msg = '当前合伙人id =>' . $curPartnerId;
        // echo $msg . "<br />";
        tLog::write($msg);

        if (0 == $toUser->is_partner) { // 收款帐号是普通用户
            // 任何级合伙人都可以给普通用户转账
            if (1 != $partner->user->is_partner) {
                $this->error('只有有辈分的才能转帐给普通用户');
            }
            if (2 != $partner->status) {
                $this->error('付款账号还未实名或者签署协议, 不能向其他人转账!');
            }
            /*
            if (5 != $partner->level->level) { // 只有最后一级才能转帐给普通用户
                $this->error('只有合伙人为粉丝用户才能转帐给普通用户');
            }
            */
            $this->transferNormalUser($partner, $toUser, $amount, $stoneType, $notice, $field);

        } else if (1 == $toUser->is_partner) { //收款账号是合伙人
            $toPartner = \app\admin\model\user\Partner::get(['user_id' => $toUser->id], ['level']);
            if (is_null($toPartner)) {
                $this->error('收款帐号不存在');
            }
            if (2 != $toPartner->status) {
                $this->error('收款账号还未实名或者签署协议, 还不能转账');
            }
            // 被转用户的推荐人信息
            if (8 == $toPartner->level_id and 8 == $partner->level_id) {
                //$this->error('2人都是全国批发商时不可转');
                $this->error('2人都是品牌方时不可转');
            }
            if (8 == $toPartner->level_id) {
                $this->error('收款人是品牌方时不可转');
            }

            $tmpParentPartner = \app\admin\model\user\Partner::get(['id' => $toPartner->parent_id]);
            $toParentPartner = \app\admin\model\user\Partner::get(['user_id' => $tmpParentPartner->user_id], ['level']);
            $toParentPartnerLevel = $toParentPartner->level->level;

            // 转账人的等级
            $partnerLevel = $partner->level->level;

            // 是否适合走公共判断条件
            $checkCommon = 1;
            // 被转账人等级
            $toPartnerLevel = $toPartner->level->level;

            // 双方都是最低等级的粉丝用户时，并且转账人是被转账人的推荐人时，可以转
            if (5 == $toPartnerLevel && 5 == $partnerLevel) { 
                if ($curPartnerId != $toPartner->dre_id) {
                    $this->error('你不是对方的推荐人');
                }
            } else {
                /*
                if ($toParentPartnerLevel < $toPartnerLevel) {
                    if ($toPartner->parent_id != $curPartnerId) {
                        if (11 == $toPartner->level_id) {
                            $this->error("只有上级和推荐人可以转账");
                        } else {
                            $this->error("只有上级可以转帐");
                        }
                    }
                    $checkCommon = 0;
                    $msg = vsprintf('推荐人等级大于收款账号等级, 只能由推荐人转账, 收款人partner ID:%s,等级:%s, 转账人partner ID:%s, 等级:%s', [$toPartner->id, $toPartnerLevel, $curPartnerId, $partnerLevel]);
                    tLog::write($msg);
                }
                // 推荐人等级等于收款账号等级
                if ($toParentPartnerLevel == $toPartnerLevel) {
                    // 收款账号是粉丝用户, 推荐人可转我
                    if ($toPartnerLevel == 5 && $toPartner->parent_id == $curPartnerId) {
                        $msg = vsprintf('推荐人等级等于收款账号等级, 收款账号是粉丝用户, 推荐人可转我, 收款人partner ID:%s,等级:%s, 转账人partner ID:%s, 等级:%s', [$toPartner->id, $toPartnerLevel, $curPartnerId, $partnerLevel]);
                        tLog::write($msg);
                        $checkCommon = 0;
                    } else {
                        // 非粉丝用户, 只能由同一条线上且离收款账号最近的人转账, 但推荐人不能转
                        if ($toPartner->parent_id == $curPartnerId) {
                            $this->error("收款账号非粉丝用户，推荐人不可转账");
                        }
                    }
                }
                // 推荐人等级小于收款账号等级
                if ($toParentPartnerLevel > $toPartnerLevel) {
                }
                */

                // 非粉丝等级时，只能是同一条推荐线上且离被转合伙人最近且等级高于被转合伙人等级时，可以转
                if ($checkCommon) {
                    // 收款账号的推荐人ID路径
                    $parentIdPathArr = explode(",", $toPartner->dre_id_path);
                    // 判断是否在同一条推荐线上
                    if (!in_array($curPartnerId, $parentIdPathArr)) {
                        // $this->error('你不是收款账号同一条推荐线上的合伙人');
                        $this->error('您此刻不能转该用户，请核实后再转');
                    }

                    // 查找所有同一条推荐线上的人的用户的级别
                    $where = [
                        'id' => ['in', $parentIdPathArr],
                    ];
                    $parentPartnersObj = \app\admin\model\user\Partner::where($where)->order('id', 'desc')->select();
                    $parentPartners = [];
                    foreach ($parentPartnersObj as $p) {
                        $parentPartners[$p->id] = $p->level->level;
                    }
                    $msg = "收款账号的合伙人等级 =>" . $toPartnerLevel;
                    // echo $msg . "<br />";
                    tLog::write($msg);
                    $gePartnerId = 0;
                    $gePartnerLevel = 0;
                    // 从路径开始找
                    foreach ($parentIdPathArr as $parentId) {
                        // 等级数值越小，等级越大的最近的上级批发商
                        if (isset($parentPartners[$parentId]) && $parentPartners[$parentId] < $toPartnerLevel) {
                            $gePartnerId = $parentId;
                            $gePartnerLevel = $parentPartners[$parentId];
                            break;
                        }
                    }
                    $msg = vsprintf('同一条推荐线上离收款账号最近且等级高于收款账号等级的, 收款人partner ID:%s,等级:%s, 转账人partner ID:%s, 等级:%s, 可转账人 partner ID:%s, 可转账人 等级：%s', [$toPartner->id, $toPartnerLevel, $curPartnerId, $partnerLevel, $gePartnerId, $gePartnerLevel]);
                    tLog::write($msg);
                    // exit;
                    if ($gePartnerId != $curPartnerId) {
                        // $this->error('当前账号非收款账号最近且大于收款账号合伙人等级的');
                        $this->error('您此刻不能转该用户，请核实后再转');
                    }
                }
            }

            $this->transfer($partner, $toPartner, $amount, $stoneType, $notice, $field);

        }

    }

    private function transferNormalUser($partner, $user, $amount, $stoneType, $notice, $field)
    {
        $partner->user->{$field} -= $amount;
        $partner->user->save();

        $user->{$field} += $amount;
        $user->save();

        Log::create([
            'type' => 1,
            'from_id' => $partner->user->id,
            'to_id' => $user->id,
            'stone_type' => $stoneType,
            'amount' => $amount,
            'notice' => $notice,
            'createtime' => Carbon::now()->getTimestamp(),
            'updatetime' => Carbon::now()->getTimestamp(),
        ]);

        $this->success('转帐成功');
    }

    private function transfer($partner, $toPartner, $amount, $stoneType, $notice, $field)
    {
        $partner->user->{$field} -= $amount;
        $partner->user->save();

        $toPartner->user->{$field} += $amount;
        $toPartner->user->save();

        Log::create([
            'type' => 1,
            'from_id' => $partner->user->id,
            'to_id' => $toPartner->user->id,
            'stone_type' => $stoneType,
            'amount' => $amount,
            'notice' => $notice,
            'createtime' => Carbon::now()->getTimestamp(),
            'updatetime' => Carbon::now()->getTimestamp(),
        ]);

        $this->success('转帐成功');
    }

    public function levelInfo()
    {
        $userId = $this->auth->id;

        $partner = \app\admin\model\user\Partner::get(['user_id' => $userId], ['level']);
        if (is_null($partner)) {
            $this->error('还不是合伙人');
        }

        $rows = Setting::with(['upgraderule'])
            ->order('level', 'desc')
            ->select();

        $rows = collection($rows)->toArray();
        $partnerLib = new PartnerLib();
        // 查找我的直接下级中各人员的当前级情况
        $subPartners = $partnerLib->getSubPartners($partner);
        // 我的直推人员
        $directNum = \app\admin\model\user\Partner::where('dre_id', $partner->id)->where('status', 2)->count();
        // 我的链上的人员
        $dreNum = \app\admin\model\user\Partner::where('find_in_set(' . $partner->id . ', dre_id_path)')->where('status', 2)->count();
        
        foreach ($rows as $key => $item) {
            $upgraderule = $rows[$key]['upgraderule'];
            $rows[$key]['total_desc'] = sprintf("我有直系家人%s人，家族有%s人", $directNum, $dreNum);
            $rows[$key]['upgraderule'] = $partnerLib->getReachDetail($upgraderule, $subPartners);

            if ($item['level'] > $partner->level->level) { // 比我当前低的
                $rows[$key]['status'] = 'done';
                $rows[$key]['upgraderule'] = array_map(function ($e) {
                    $e['is_done'] = 1;
                    foreach ($e['reach_detail'] as &$r) {
                        $r['is_reach'] = 1;
                        $r['reach_amount'] = $r['amount'];
                        $r['reach_desc'] = sprintf('带领%s位以上兄弟姐妹共创财富', $r['amount']);
                    }
                    if (1 == $e['type']) {
                        $e['type_desc'] = sprintf('我的宝贝家人要有%s人', $e['amount']);
                    } else if (2 == $e['type']) {
                        $e['type_desc'] = sprintf('家族总人口达到%s人', $e['amount']);
                    }
                    unset($r);
                    return $e;
                }, $rows[$key]['upgraderule']);
                $rows[$key]['upgrade_button_enabled'] = false;
            }
            if ($item['level'] == $partner->level->level) {  // 我是当前级，我要做到的rule, 才能升下一级
                $rows[$key]['status'] = 'onprogress';
                $rows[$key]['upgraderule'] = array_map(function ($e) use ($partner) {
                    if (1 == $e['type']) {
                        // 推荐人员 
                        $count = \app\admin\model\user\Partner::where('dre_id', $partner->id)->where('status', 2)->count();
                        $e['current_amount'] = $count;
                        $isDone = 1;
                        // 首先需要完成总数
                        if ($count >= $e['amount']) {
                            foreach ($e['reach_detail'] as $r) {
                                if ($r['is_reach'] == 0) {
                                    $isDone = 0;
                                }
                            }
                        } else {
                            $isDone = 0;
                        }
                        $e['is_done'] = $isDone;
                        // 未完成时
                        $e['type_desc'] = sprintf('我的宝贝家人要有%s人，当前已有%s人', $e['amount'], $count);
                    } else if (2 == $e['type']) {
                        // 总业绩
                        $count = \app\admin\model\user\Partner::where('find_in_set(' . $partner->id . ', dre_id_path)')->where('status', 2)->count();
                        $e['current_amount'] = $count;
                        if ($count >= $e['amount']) {
                            $e['is_done'] = 1;
                        } else {
                            $e['is_done'] = 0;
                        }
                        // 未完成时
                        $e['type_desc'] = sprintf('家族总人口达到%s人，当前已有%s人', $e['amount'], $count);
                    }
                    return $e;
                }, $rows[$key]['upgraderule']);
                $upgradeButtonEnabled = false;
                foreach ($rows[$key]['upgraderule'] as $v) {
                    if (1 == $v['is_done']) {
                        $upgradeButtonEnabled = true;
                    } else {
                        $upgradeButtonEnabled = false;
                        break;
                    }
                }
                $rows[$key]['upgrade_button_enabled'] = $upgradeButtonEnabled;
            }
            if ($item['level'] < $partner->level->level) {
                $rows[$key]['status'] = 'nostart';
                $rows[$key]['upgraderule'] = array_map(function ($e) {
                    $e['is_done'] = 0;
                    foreach ($e['reach_detail'] as &$r) {
                        $r['reach_desc'] = sprintf('带领%s位以上兄弟姐妹共创财富', $r['amount']);
                    }
                    if (1 == $e['type']) {
                        $e['type_desc'] = sprintf('我的宝贝家人要有%s人', $e['amount']);
                    } else if (2 == $e['type']) {
                        $e['type_desc'] = sprintf('家族总人口达到%s人', $e['amount']);
                    }
                    return $e;
                }, $rows[$key]['upgraderule']);
                $rows[$key]['upgrade_button_enabled'] = false;
            }
        }

        $this->success('ok', $rows);

    }

    public function doLevelUpgrade()
    {
        $userId = $this->auth->id;
        $partner = \app\admin\model\user\Partner::get(['user_id' => $userId]);
        if (is_null($partner)) {
            $this->error('还不是合伙人');
        }

        $level = $partner->level_id;

        // check是否可以升级
        $row = Setting::get($partner->level_id, ['upgraderule'])->toArray();
        $partnerLib = new PartnerLib();
        // 查找我的直接下级中各人员的当前级情况
        $subPartners = $partnerLib->getSubPartners($partner);
        $upgraderule = $row['upgraderule'];
        $row['upgraderule'] = $partnerLib->getReachDetail($upgraderule, $subPartners);

        $row['upgraderule'] = array_map(function ($e) use ($partner) {
            if (1 == $e['type']) {
                $count = \app\admin\model\user\Partner::where('dre_id', $partner->id)->where('status', 2)->count();
                $e['current_amount'] = $count;
                $isDone = 1;
                // 首先需要完成总数
                if ($count >= $e['amount']) {
                    foreach ($e['reach_detail'] as $r) {
                        if ($r['is_reach'] == 0) {
                            $isDone = 0;
                        }
                    }
                } else {
                    $isDone = 0;
                }
                $e['is_done'] = $isDone;
            } else if (2 == $e['type']) {
                $count = \app\admin\model\user\Partner::where('find_in_set(' . $partner->id . ', dre_id_path)')->where('status', 2)->count();
                $e['current_amount'] = $count;
                if ($count >= $e['amount']) {
                    $e['is_done'] = 1;
                } else {
                    $e['is_done'] = 0;
                }
            }
            return $e;
        }, $row['upgraderule']);
        $canUpgrade = false;
        foreach ($row['upgraderule'] as $v) {
            if (1 == $v['is_done']) {
                $canUpgrade = true;
            } else {
                $canUpgrade = false;
                break;
            }
        }

        if ($canUpgrade) {
            $upLevelId = \app\admin\model\user\Partner::getUpLevel($level);
            $upLevelObj = Setting::get($upLevelId);

            // 20250113修改为 我得上级批发商：统一显示为同一条推荐线上级别高于我且离我最近得批发商
            // 当前账户的推荐人ID路径
            $parentIdPathArr = explode(",", $partner->dre_id_path);

            // 查找所有同一条推荐线上的人的用户的级别
            $where = [
                'id' => ['in', $parentIdPathArr],
            ];
            $parentPartnersObj = \app\admin\model\user\Partner::where($where)->order('id', 'desc')->select();
            $parentPartners = [];
            foreach ($parentPartnersObj as $p) {
                $parentPartners[$p->id] = $p->level->level;
            }
            $msg = vsprintf("partner id: %s, 要升级的级别ID: %s, 定义级别值:%s", [$partner->id, $upLevelId, $upLevelObj->level]);
            // echo $msg . "<br />";
            tLog::write($msg);
            $gePartnerId = null;
            // 从路径开始找
            foreach ($parentIdPathArr as $parentId) {
                // 等级数值越小，等级越大的最近的上级批发商
                if (isset($parentPartners[$parentId]) && $parentPartners[$parentId] < $upLevelObj->level) {
                    $gePartnerId = $parentId;
                    break;
                }
            }
            // echo $gePartnerId;exit;
            /*
            // 暂时不更新parent_id_path, 平台整体使用dre_id_path去查询
            if (!empty($gePartnerId)) {
                $parentPartner = \app\admin\model\user\Partner::get($gePartnerId);
                $partner->parent_id_path = $parentPartner->parent_id_path;
            } else {
                $partner->parent_id_path = null;
            }
            */

            $partner->parent_id = $gePartnerId;
            $partner->level_id = $upLevelId;
            $partner->save();

            $this->success('恭喜你，升级为' . $upLevelObj->level_name);
        } else {
            $this->error('当前还未达到升级条件');
        }
    }

    public function myTeam()
    {
        $limit = 10;
        $page = input('get.page', 1);
        $searchName = input('get.name');
        $levelId = input('get.level_id');

        $userId = $this->auth->id;
        $partner = \app\admin\model\user\Partner::get(['user_id' => $userId]);
        if (is_null($partner)) {
            $this->error('还不是合伙人');
        }

        $model = new \app\admin\model\user\Partner;
        $list = $model
            ->with(['level'])
            ->where('status', '=', 2)
           // ->where('find_in_set(' . $partner->id . ', dre_id_path)');
            ->where('dre_id', '=', $partner->id);

        if (!empty($searchName)) {
            $list->where('realname', 'like', "%$searchName%");
        }

        if (is_numeric($levelId)) {
            $list->where('level_id', $levelId);
        }

        $list = $list->paginate($limit, false, ['page' => $page])->each(function ($item, $key) {
            //总业绩值不要了
//            $item->total_achievement = \app\admin\model\user\Partner::where('find_in_set(' . $item->id . ', dre_id_path)')->count();
            $item->user = User::get($item->user_id);
        });

        $this->success('ok', $list);
    }

    public function memberInfo()
    {
        $partnerId = input('get.partnerid');
//        $partnerId = 30;
        $partner = \app\admin\model\user\Partner::get($partnerId, ['user', 'level']);
        $partner->total_achievement = \app\admin\model\user\Partner::where('find_in_set(' . $partnerId . ', dre_id_path)')->count();
        $partner->dre_num = \app\admin\model\user\Partner::where('dre_id', $partnerId)->count();

        $this->success('ok', $partner);
    }

    public function levels()
    {
        $levels = Setting::order('level', 'asc')->select();
        $this->success('ok', $levels);
    }

    public function qrcode()
    {
        $partnerId = input('get.partnerid');
        $partner = \app\admin\model\user\Partner::get($partnerId, ['user']);
        if (is_null($partner)) {
            $this->error('还不是合伙人');
        }
        if (2 != $partner->status) {
            $this->error('此合伙人还没有认证和签署协议');
        }

        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $domain = $_SERVER['HTTP_HOST'];

        $url = "$protocol://$domain" . '/pages/second/partner?realname=' . $partner->realname . '&account=' . $partner->partner_account;

        $qrCodeUrl = addon_url('qrcode/index/build', ['text' => $url, 'size' => 200, 'padding' => 0], '', true);

        $this->success('ok', [
            'qrcode_url' => $qrCodeUrl
        ]);

    }

    public function checkFileIssigned()
    {
        $userId = $this->auth->id;
        $partner = \app\admin\model\user\Partner::get(['user_id' => $userId]);
        if (is_null($partner)) {
            $this->error('还不是合伙人');
        }
        $fileNo = input('file_no');

        $row = Sign::get(['partner_id' => $partner->id]);

        $isSigned = 0;
        if ($row) {
            if (1 == $fileNo) {
                if ($row->file_one_signature_image) {
                    $isSigned = 1;
                } else {
                    $isSigned = 0;
                }
            }
            if (2 == $fileNo) {
                if ($row->file_two_signature_image) {
                    $isSigned = 1;
                } else {
                    $isSigned = 0;
                }
            }
        } else {
            $isSigned = 0;
        }

        $this->success('ok', [
            'is_signed' => $isSigned
        ]);

    }

    public function checkHasVipQualifiction()
    {
        $userId = $this->auth->id;

        $isPartner = \app\admin\model\user\Partner::get(['user_id' => $userId]);

        $hasInvited = Apply::where('apply_id', $userId)
            ->whereIn('status', 1)
            ->count();

        $this->success('ok', [
            'has_qualification' => $isPartner or $hasInvited
        ]);
    }

}
